package com.dongdongshop.logaop;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 使用springAOP打印日志  切面类
 * @Author Eayon
 * @Date 2020/2/22 9:31
 */
@Aspect //切面类
@Component
public class LogAspect {
    private Logger logger = LoggerFactory.getLogger(LogAspect.class);

    /**
     * 切点表达式方法
     * service爆红因为common没有service，不用关心他
     * 这里去除掉了controller的一个文件上传方法，因为该方法的参数类型无法进行json tostring 的解析
     * 在controller中有参数不能解析而产生aop和json错误的，可以在这里去除报错的方法
     */
    @Pointcut("execution(public * com.dongdongshop.service..*.*(..)) || execution(public * com.dongdongshop.controller..*.*(..))" +
            "&& !execution(public * com.dongdongshop.controller..GoodsController.upLoadFile(..))" +
            "&& !execution(public * com.dongdongshop.controller..ContentController.upLoadFile(..))" +
            "&& !execution(public * com.dongdongshop.controller..CartController.getCart(..))" +
            "&& !execution(public * com.dongdongshop.controller..CartController.addGoodsToCartList(..))" +
            "&& !execution(public * com.dongdongshop.controller..CartController.delCartOrderItem(..))" +
            "&& !execution(public * com.dongdongshop.controller..CartController.toCartList(..))" +
            "&& !execution(public * com.dongdongshop.controller..UserHomeController.addevaluate(..))")
    public void aopLog(){
    }

    /**
     * 定义前置通知
     */
    @Before("aopLog()")
    public void doBefore(JoinPoint joinPoint){
        //获取参数
        Object[] args = joinPoint.getArgs();
        //获取方法名
        Signature signature = joinPoint.getSignature();
        logger.info("正在执行方法：{}，参数为：{}",signature, JSON.toJSONString(args));
    }

    /**
     * 定义返回后通知
     */
    @AfterReturning(pointcut = "aopLog()", returning = "ret")
    public void doAfterReturning(Object ret){
        //处理请求成功后，打印返回结果
        logger.info("方法执行成功，返回结果为: {}", JSON.toJSONString(ret));
    }
}
